package com.thinkit.security.custom;

import com.thinkit.cms.dto.admin.UserDto;
import com.thinkit.core.constant.SecurityConstants;
import com.thinkit.security.login.LoginService;
import com.thinkit.utils.enums.UserFrom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @ClassName: MyUserDetailsService
 * @Author: LG
 * @Date: 2019/3/7 11:54
 * @Version: 1.0
 **/
@Component(SecurityConstants.PLAT_USER_DETAILS_SERVICE)
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    CustomUserLoginRiskCheck customUserLoginRiskCheck;

    @Autowired
    LoginService loginService;

    @Override
    public UserDetails loadUserByUsername(String userAccount)throws UsernameNotFoundException {
        customUserLoginRiskCheck.loginRiskCheck(userAccount, UserFrom.PLAT_USER.getClientId(),true);
        UserDto userDto=loginService.loadUserByUsername(userAccount);
        if (userDto == null) {
            throw new UsernameNotFoundException("账号或密码不正确!");
        }
        // 账号锁定
        if (userDto.getStatus() == 1) {
            throw new LockedException("账号已被锁定,请联系管理员");
        }
        Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        CustomJwtUser customJwtUser=new CustomJwtUser(userDto.getId(),userDto.getOrgId(),userDto.getUserAccount(),userDto.getPassword(),userDto.getRoleSign(),
        grantedAuthorities);
        return customJwtUser;
    }
}
